package chen.jia.xin.finalproject.MainView;

import android.Manifest;
import android.app.ActionBar;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import org.litepal.LitePal;
import java.util.ArrayList;
import java.util.List;
import chen.jia.xin.finalproject.BaseActivity;
import chen.jia.xin.finalproject.DownloadService;
import chen.jia.xin.finalproject.LogView.UserAndFriends;
import chen.jia.xin.finalproject.R;
import chen.jia.xin.finalproject.MainView.AllItemAdapter.Callback;

public class MainActivity extends BaseActivity implements Callback,AdapterView.OnClickListener {

    //所有显示的图标的List
    private List<AllItem> listItems = new ArrayList<>();
    //登录的用户的好友列表
    private List<String> userAllFriends = new ArrayList<>();
    //显示对应的用户名
    private TextView showUserName;
    //实现好友搜索功能
    private EditText editText;
    private ImageView search_friend;
    //实现编辑键功能(操作数据库litepal)
    private Button edit;
    private AllItemAdapter allItemAdapter;
    private ListView listView;
    //切换用户状态菜单弹出
    private Button statusChangeButton;
    private Button download_bt;
    //服务与活动连接

    private DownloadService.DownloadBinder downloadBinder;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (DownloadService.DownloadBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    @Override
    public void onBackPressed() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        //显示对应的用户名
        showUserName = findViewById(R.id.user_Name);
        Intent intent = getIntent();
        showUserName.setText("Hello: "+intent.getStringExtra("userName"));
        //添加自定义的标题(先隐藏自带的ActionBar)
        ActionBar actionBar = getActionBar();
        if(actionBar != null){
            actionBar.hide();
        }
        //开启服务
        Intent intentService = new Intent(this, DownloadService.class);
        startService(intentService);
        //绑定服务
        bindService(intentService, connection, BIND_AUTO_CREATE);
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
            Toast.makeText(MainActivity.this, "没有下载权限", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(MainActivity.this, "有下载权限", Toast.LENGTH_SHORT).show();
        }

        //登录后首先查看数据库中用户对应的好友是否存在
        //1.存在的话就加载List  2.否则初始化再加载List
        List<UserAndFriends> users = null;
        //在数据库中查询query
        try {
            users = LitePal.where("userName = ?",intent.getStringExtra("userName")).find(UserAndFriends.class);
            if (users.isEmpty()) {
                userAllFriends.add("李雨桐");
                userAllFriends.add("刘光洪");
                userAllFriends.add("李潘");
                userAllFriends.add("迪丽热巴");
                userAllFriends.add("石原");
                userAllFriends.add("宋祖儿");
                userAllFriends.add("李贵洋");
                userAllFriends.add("王琴");
            } else {
                for (UserAndFriends userAndFriend: users){
                    userAllFriends.add(userAndFriend.getUserName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //实现好友搜索功能
        editText = findViewById(R.id.search_friend_text);
        editText.setOnClickListener(this);
        search_friend = findViewById(R.id.search_friend_image);
        search_friend.setOnClickListener(this);

        //实现编辑键功能(操作数据库litepal)
        edit = findViewById(R.id.title_edit);
        edit.setOnClickListener(this);

        //初始化所有图标
        initAllItems();
        allItemAdapter = new AllItemAdapter(MainActivity.this,R.layout.all_item,listItems,this);
        listView = findViewById(R.id.listView);
        listView.setAdapter(allItemAdapter);
        //添加List单击点击事件(与好友聊天)
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AllItem eachItem = listItems.get(position);
                //传递好友名的参数给Intent
                Intent intent = new Intent(MainActivity.this, ChatActivity.class);
                intent.putExtra("friendName", eachItem.getImageName());
                startActivity(intent);
            }
        });


        //长按ListView显示菜单
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, final View view, final int position, long id) {
                //用户名信息
                try {
                    PopupMenu popupMenu = new PopupMenu(MainActivity.this,view);
                    popupMenu.inflate(R.menu.showuserallinfo);
                    popupMenu.show();
                    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem item) {
                            switch (item.getItemId()) {
                                case R.id.delete_user:
                                    listItems.remove(position);
                                    //删除好友后通知适配器刷新
                                    allItemAdapter.notifyDataSetChanged();
                                    break;
                                case R.id.focus_user:
                                    //输入对应item的Button的View
                                    AllItemAdapter.isSelect.put(position, true);
                                    allItemAdapter.notifyDataSetChanged();
                                    break;
                            }
                            return true;
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        });

        //切换用户状态菜单弹出
        statusChangeButton = findViewById(R.id.forceOut);
        statusChangeButton.setOnClickListener(this);

        download_bt = findViewById(R.id.download_bt);
        //通过service实现下载文件的功能
        download_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                //注意Activity的名字与关键字冲突
//                Intent intent = new Intent(MainActivity.this,NotificationActivity.class);
//                //注意这里是静态方法得到实例
//                PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,0);
//                //创建通知管理者
//                NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//                //创建通知通道(最新API方法)
//                NotificationChannel notificationChannel = new NotificationChannel("1","channel",NotificationManager.IMPORTANCE_HIGH);
//                //添加通道
//                notificationManager.createNotificationChannel(notificationChannel);
//                Notification notification = new NotificationCompat.Builder(MainActivity.this,"1")
//                        .setContentTitle("TIM_Message")
//                        .setContentText("你的TIM好友Lyt已上线~~~")
//                        .setWhen(System.currentTimeMillis())
//                        .setSmallIcon(R.mipmap.ic_launcher)
//                        .setContentIntent(pendingIntent)
//                        .build();
//                notificationManager.notify(1,notification);
                //弹出Pop菜单
                PopupMenu popupMenu = new PopupMenu(MainActivity.this,v);
                popupMenu.inflate(R.menu.downloadfile);
                popupMenu.show();
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.start_download:
                                String url = "https://code.visualstudio.com/docs/?dv=win64user";
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                    downloadBinder.startDownload(url);
                                }
                                break;
                            case R.id.pause_download:
                                downloadBinder.pauseDownload();
                                break;
                            case R.id.cancel_download:
                                downloadBinder.cancelDownload();
                                break;
                        }
                        return true;
                    }
                });
            }
        });
    }

    //
    private void initAllItems(){
        for (int i = 0;i<2;i++){
            AllItem email = new AllItem(R.drawable.email,"李雨桐");
            listItems.add(email);
            AllItem gallery = new AllItem(R.drawable.gallery,"刘光洪");
            listItems.add(gallery);
            AllItem gm = new AllItem(R.drawable.gm,"李潘");
            listItems.add(gm);
            AllItem lock = new AllItem(R.drawable.lock,"迪丽热巴");
            listItems.add(lock);
            AllItem maps = new AllItem(R.drawable.maps,"石原");
            listItems.add(maps);
            AllItem monitor = new AllItem(R.drawable.monitor,"宋祖儿");
            listItems.add(monitor);
            AllItem music = new AllItem(R.drawable.music,"李贵洋");
            listItems.add(music);
            AllItem notes = new AllItem(R.drawable.notes,"王琴");
            listItems.add(notes);
        }
    }

    //实现Callback回调接口中的方法
    @Override
    public void click(AllItemAdapter.ViewHolder viewHolder) {
        //设置为特别关心的提醒
        if(viewHolder.chatButton.getTag(R.id.btn).equals(true)) {
            Toast.makeText(this, "已成功添加特别关心" , Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "已成功取消特别关心" , Toast.LENGTH_SHORT).show();
        }
    }

    //实现View.OnClickListener接口的方法
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_friend_image:
                boolean checkResult = false;
                for (String check : userAllFriends) {
                    if (check.equals(editText.getText().toString())) {
                        checkResult = true;
                    }
                }
                if (checkResult) {
                    android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("查询结果");
                    builder.setMessage("你的好友已上线");
                    builder.setCancelable(false);
                    builder.setPositiveButton("Sure~", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    builder.show();
                }
                else {
                    android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("查询结果");
                    builder.setMessage("你的好友还没有上线");
                    builder.setCancelable(false);
                    builder.setPositiveButton("Sure~", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    builder.show();
                }
                break;
            case R.id.title_edit:
                Intent intent = new Intent(MainActivity.this,LitepalOperation.class);
                startActivity(intent);
                break;
            case R.id.forceOut:
                //弹出Pop菜单
                PopupMenu popupMenu = new PopupMenu(MainActivity.this,v);
                popupMenu.inflate(R.menu.statuschange);
                popupMenu.show();
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.on_line:
                                break;
                            case R.id.hiding:
                                break;
                            case R.id.off_line:
                                Intent intent = new Intent("com.example.broadcastbestpractice.FORCE_OFFLINE");
                                sendBroadcast(intent);
                                break;
                        }
                        return true;
                    }
                });
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1 :
                if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this,"拒绝权限将无法使用程序",Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }
}
